package com.heima.behavior.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.service.IApPariseService;
import com.heima.behavior.service.IApUnlikeService;
import com.heima.common.constants.KafkaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApParise;
import com.heima.model.behavior.pojos.ApUnlike;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.UserThreadLocal;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 文章点赞表 前端控制器
 * </p>
 *
 * @author fkn
 * @since 2024-08-21
 */
@RestController
public class ApPariseController {

    @Resource
    private IApPariseService pariseService;

    @Resource
    private IApUnlikeService unlikeService;

    private final static short LIKE_NUM = 0;

    @Resource
    private KafkaTemplate<String,String> kafkaTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final static String LIKE = "LIKE";
    private final static String UNLIKE = "UNLIKE";

    @PostMapping("/api/v1/likes_behavior")
    public ResponseResult likeArticle(@RequestBody @Valid LikesBehaviorDto dto){
        ValueOperations<String, String> operation = stringRedisTemplate.opsForValue();
        Integer userId = UserThreadLocal.get();
        ApParise apParise = ApParise.builder().articleId(dto.getArticleId()).userId(userId)
                .type(ApParise.type.ARTICLE.getCode()).pariseTime(LocalDateTime.now()).build();
        if (LIKE_NUM == dto.getOperation()){
            //幂等性
            if (!operation.setIfAbsent(LIKE + userId,"1",1, TimeUnit.SECONDS)){
                throw new CustomException(AppHttpCodeEnum.NOT_REPETITION_OPERATION);
            }
            kafkaTemplate.send(KafkaConstants.BEHAVIOR_LIKE, JSON.toJSONString(apParise));
            //pariseService.like(dto);
        }else {
            //幂等性
            if (!operation.setIfAbsent(UNLIKE + userId,"1",1, TimeUnit.SECONDS)){
                throw new CustomException(AppHttpCodeEnum.NOT_REPETITION_OPERATION);
            }
            apParise.setUserId(userId);
            kafkaTemplate.send(KafkaConstants.BEHAVIOR_UNLIKE, JSON.toJSONString(apParise));
            //pariseService.unlike(dto);
        }
        return ResponseResult.okResult(null);
    }

    @PostMapping("/like_and_unlike")
    public ResponseResult likeAndUnlike(@RequestBody ArrayList<Object> ids){
        Integer userId = (Integer) ids.get(0);
        Long articleId = Long.parseLong((String) ids.get(1));
        ArrayList<Boolean> booleans = new ArrayList<>();
        LambdaQueryWrapper<ApParise> likeCondition = new LambdaQueryWrapper<ApParise>()
                .eq(ApParise::getUserId, userId)
                .eq(ApParise::getArticleId, articleId);
        booleans.add(pariseService.getOne(likeCondition) != null);
        LambdaQueryWrapper<ApUnlike> unlikeCondition = new LambdaQueryWrapper<ApUnlike>()
                .eq(ApUnlike::getUserId, userId)
                .eq(ApUnlike::getArticleId, articleId);
        booleans.add(unlikeService.getOne(unlikeCondition) != null);
        return ResponseResult.okResult(booleans);
    }
}
